/*
 * Copyright 2004 original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jbfilter.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.jbfilter.bean.FilterBean;
import org.jbfilter.bean.FilterComponentBean;
import org.jbfilter.bean.factory.FilterBeans;
import org.jbfilter.core.FilterComponent;
import org.jbfilter.hibernate.FilterComponentHibernate;
import org.jbfilter.hibernate.FilterHandlerHibernate;
import org.jbfilter.hibernate.FilterHibernate;

/**
 * Supports {@link FilterComponentHibernate}'s ans {@link FilterComponentBean}'s.
 * @author Marcus Adrian
 * @param <E>
 */

class _FilterHibernateHybridImpl<E>
	extends
		_FilterImpl<E>
	implements
		FilterHibernate<E> {

	private FilterHibernate<E> filterHibernate = new _FilterHibernateImpl<E>();
	private FilterBean<E> filterBean = FilterBeans.newFilter();
	
	_FilterHibernateHybridImpl(SessionFactory sessionFactory) {
		super();
		setSessionFactory(sessionFactory);
	}

	_FilterHibernateHybridImpl() {
		super();
	}
	
	@Override
	public List<E> filter(Class<E> clazz, Session session) {
		return makeBeanFiltering(filterHibernate.filter(clazz, session));
	}

	@Override
	public List<E> filter(Class<E> clazz) {
		return makeBeanFiltering(filterHibernate.filter(clazz));
	}
	private List<E> makeBeanFiltering(List<E> hibFiltered) {
		// TODO size dans FilterComponents ?
		if (filterBean.getFilterComponents().size() != 0) {
			return filterBean.filter(hibFiltered);
		} else {
			return hibFiltered;
		}
	}
	@Override
	public void setSessionFactory(SessionFactory sessionFactory) {
		filterHibernate.setSessionFactory(sessionFactory);
	}

	@Override
	public void addFilterComponent(FilterComponent<E> fcomp) {
		super.addFilterComponent(fcomp);
		if (fcomp instanceof FilterComponentHibernate) {
			filterHibernate.addFilterComponent((FilterComponentHibernate<E>)fcomp);
		} else if (fcomp instanceof FilterComponentBean) {
			filterBean.addFilterComponent((FilterComponentBean<E>)fcomp);
		} else {
			throw new IllegalArgumentException("expected : " + FilterComponentBean.class + " or " + FilterComponentHibernate.class + ".");
		}
	}
	@Override
	public FilterHandlerHibernate<E> newFilterHandler() {
		return new FilterHandlerHibernate<E>(this);
	}

}
